package com.ruby.bigtable.spark;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaPairInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.kafka.KafkaUtils;

import kafka.serializer.StringDecoder;
import scala.Tuple2;

public class WordCountKafkaDirect {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("Word Count");
		JavaStreamingContext jssc = new JavaStreamingContext(conf, Durations.seconds(5));
		
		Map<String, String> brokerList = new HashMap<String, String>();
		brokerList.put("meta.broker.list", "127.0.0.1:2181");
		Set<String> topicSet = new HashSet<String>();
		topicSet.add("WordCount");
		
		JavaPairInputDStream<String, String> lineDStream = KafkaUtils.createDirectStream(jssc, String.class, String.class, StringDecoder.class, StringDecoder.class, brokerList, topicSet);
	
		JavaDStream<String> wordRdd = lineDStream.flatMap(new FlatMapFunction<Tuple2<String,String>, String>() {

			private static final long serialVersionUID = 1L;

			public Iterable<String> call(Tuple2<String, String> t) throws Exception {
				// TODO Auto-generated method stub
				return Arrays.asList(t._2.split(" "));
			}
		});
		
		JavaPairDStream<String, Integer> wordPair = wordRdd.mapToPair(new PairFunction<String, String, Integer>() {

			private static final long serialVersionUID = 1L;

			public Tuple2<String, Integer> call(String t) throws Exception {
				// TODO Auto-generated method stub
				return new Tuple2<String, Integer>(t, 1);
			}
		});
		
		JavaPairDStream<String, Integer> resRdd = wordPair.reduceByKey(new Function2<Integer, Integer, Integer>() {
			
			public Integer call(Integer v1, Integer v2) throws Exception {
				// TODO Auto-generated method stub
				return v1+v2;
			}
		});
		
		resRdd.print();
		
		jssc.start();
		jssc.awaitTermination();
		jssc.stop();
	}

}
